window.addEventListener('load', async () => {
    const url = "http://localhost:1628/production/auth/noPermission.html";
    try {
        //获取cookie
        const token = _getCookie("authorization");
        //无token跳转无权限页面
        if (!token) {
            window.location.replace(url);
        }
        //鉴权
        const result = await _myFetch('http://localhost:1628/production/controller/auth/VerifyToken', {token});
        const body = await result.json();
        //鉴权失败跳转无权限页面
        if (!body.data) {
            console.log(1);
            window.location.replace(url);
        }
        //解析token
        const analyzeToken = _analyzeToken(token);
        //token过期前一天请求新的token
        if (Date.now() < analyzeToken.exp * 1000 && Date.now() + 24 * 60 * 60 * 1000 > analyzeToken.exp * 1000) {
            const refreshResult = await _myFetch("http://localhost:1628/production/controller/auth/GetToken", {token});
            const refreshBody = await refreshResult.json();
            //token刷新失败，跳转无权限页面
            if (!refreshBody.data) {
                window.location.replace(url);
            }
        }

        function _getCookie(name) {
            console.log(document.cookie)
            let cookies = document.cookie.split("; ");
            for (let val of cookies) {
                console.log(val.trim());
                if (val.split("=")[0] === name) {
                    return val.split("=")[1];
                }
            }
        }

        function _analyzeToken(token) {
            let strings = token.split(".");
            return JSON.parse(decodeURIComponent(encodeURIComponent(window.atob(strings[1].replace(/-/g, "+").replace(/_/g, "/")))));
        }

        async function _myFetch(url, body) {
            return await fetch(url, {
                'method': 'POST',
                'headers': {
                    "Access-Control-Allow-Origin": '*',
                    'Access-Control-Allow-Methods': '*',
                    'Access-Control-Allow-Headers': '*',
                    'Content-Type': 'application/json'
                },
                'body': JSON.stringify(body)
            });
        }
    } catch (err) {
        console.error(err);
        alert("鉴权请求失败");
        window.location.replace(url);
    }
})